<?php

namespace app\customer\controller\spread\rongcui;

use app\rongcui\model\AreasModel;
use app\rongcui\model\CustomerNatureModel;
use app\rongcui\model\RongcuiBuyerModel;
use app\rongcui\model\RongcuiBuyerUserModel;
use app\rongcui\model\RongcuiIndustryCateModel;
use app\rongcui\model\RongcuiIndustryTypeModel;

class BuyerController extends \app\rongcui\controller\BuyerController
{
    function index() {
        $where = [];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['buser.uid'] = ['in', $users];
        }
        $cate_id = input('category','-1');
        if($cate_id != -1) {
            $where['ctype.cate_id'] = $cate_id;
        }
        if (input('source')) {
            $where['buyer.source'] = input('source');
        }
        if (input('nature')) {
            $where['buyer.nature'] = input('nature');
        }
        if (input('is_done')) {
            $where['buyer.is_done'] = input('is_done', 0, 'intval') - 1;
        }
        if (input('start_time')) {
            $where['buyer.createtime'] = ['gt', strtotime(input('start_time'))];
        }
        if (input('end_time')) {
            $endtime = strtotime(input('end_time'));
            $datetime = strtotime(date('Y-m-d', $endtime));
            if ($endtime == $datetime) {
                $endtime += 86399;
            }
            if (isset($where['buyer.createtime'])) {
                $where['buyer.createtime'] = ['BETWEEN', [strtotime(input('start_time')), $endtime]];
            } else {
                $where['buyer.createtime'] = ['lt', $endtime];
            }
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['buyer.name|buyer.phone|buyer.remark'] = ['like', "%$keyword%"];
        }

        $buyerModel = new RongcuiBuyerModel();
        $lists = $buyerModel
            ->alias('buyer')
            ->join('__RONGCUI_BUYER_USER__ buser', 'buyer.id = buser.pid and buser.level = 1')
            ->join('__USER__ user', 'buser.uid = user.id')
            ->join('__USER__ luser', 'buyer.lock_uid = luser.id','left')
            ->join('__RONGCUI_INDUSTRY_TYPE__ ctype', 'buyer.id = ctype.pid')
            ->join('__CUSTOMER_NATURE__ nature', 'buyer.nature = nature.id','left')
            ->group('buyer.id')
            ->where('char_length(buyer.name) <= 8')
            ->where($where)
            ->field([
                'buyer.*',
                'nature.name nname',
                'user.user_nickname',
                'luser.user_nickname lname'
            ])
            ->order('buyer.createtime desc,buyer.id desc')
            ->paginate();

        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel->where([
            'status' => 1,
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $customerNatureModel = new CustomerNatureModel();
        $source = $customerNatureModel->where([
            'type' => 2,
            'is_del' => 0
        ])->field('id,name')->select();

        $nature = $customerNatureModel->where([
            'type' => 8,
            'is_del' => 0
        ])->field('id,name')->select();

        $where_r = input();
        $lists->appends($where_r);
        $page = $lists->render();

        $this->assign('lists', $lists);
        $this->assign('source', $source);
        $this->assign('nature', $nature);
        $this->assign('where_r', $where_r);
        $this->assign('page', $page);
        $this->assign('cate', $cate);
        return $this->fetch();
    }



    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        if ($this->request->isPost()) {
            $this->addPost(1);
        }
        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel
            ->where([
                'status' => 1,
                'is_del' => 0
            ])->order('parent_id,list_order,id')->select();

        $this->assign('areaslist', $areaslist);
        $this->assign('cate', $cate);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function edit() {
        $id = $this->request->param('id', 0, 'intval');
        if(!$id) {
            $this->error('访问错误！');
        }
        $buyerModel = new RongcuiBuyerModel();
        if($this->request->isPost()) {
            $arrData = $this->request->post();
            if(!isset($arrData['manager'])) {
                $arrData['manager'] = cmf_get_current_admin_id();
            }

            if(isset($arrData['createtime'])) {
                $arrData['createtime'] = strtotime($arrData['createtime']);
                if (!$arrData['createtime']) {
                    $arrData['createtime'] = time();
                }
            }else{
                $arrData['createtime'] = time();
            }

            if(isset($arrData['cid'])) {
                $cids = explode(',', $arrData['cid']);
                if (!$cids) {
                    $this->error('行业类别不能为空');
                }
                $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
                $cate = $rongcuiIndustryCateModel->find($arrData['cid']);
                $arrData['cname'] = $cate['name'];
                $data = [];
                foreach ($cids as $cid) {
                    $data[] = [
                        'pid' => $arrData["id"],
                        'cate_id' => $cid,
                        'level' => 1
                    ];
                }
            }

            $result = $buyerModel->allowField(true)->validate('rongcui/RongcuiBuyer')->save($arrData, ["id" => $arrData["id"]]);
            if ($result !== false) {
                if(isset($data)) {
                    $rongcuiIndustryTypeModel = new RongcuiIndustryTypeModel();
                    $rongcuiIndustryTypeModel->where(['pid' => $arrData['id'], 'level' => 1])->delete();
                    $rongcuiIndustryTypeModel->allowField(true)->saveAll($data);
                }

                $buyerUserModel = new RongcuiBuyerUserModel();
                $buyerUserModel->allowField(true)->save(['uid' => $arrData['manager']], ['pid' => $buyerModel->id, 'level' => 2]);

                $this->success(lang("保存成功"), url("index"));
            } else {
                $this->error($buyerModel->getError());
            }
        }
        $result = $buyerModel
            ->alias('buyer')
            ->join('__USER__ user', 'buyer.manager = user.id', 'left')
            ->join('__CUSTOMER_NATURE__ nature', 'buyer.source = nature.id and nature.type = 2', 'left')
            ->join('__CUSTOMER_NATURE__ nature_level', 'buyer.customer_level = nature_level.id and nature_level.type = 3', 'left')
            ->join('__CUSTOMER_NATURE__ ntru', 'buyer.nature = ntru.id and ntru.type = 8', 'left')
            ->field([
                'buyer.*',
                'user.user_nickname as mname',
                'nature.name as nname',
                'nature_level.name as level_name',
                'ntru.name as nature_name'
            ])
            ->where(['buyer.id' => $id])->find();

        $rongcuiIndustryCateModel = new RongcuiIndustryCateModel();
        $cate = $rongcuiIndustryCateModel->where([
            'status' => 1,
            'is_del' => 0
        ])->order('parent_id,list_order,id')->select();

        $areas = new AreasModel();
        $areaslist = $areas->where(['parentid' => 0])->order('sort')->select()->toArray();

        $this->assign('areaslist', $areaslist);
        $this->assign('result', $result);
        $this->assign('cate', $cate);
        return $this->fetch();
    }
}